<?php

namespace Common\Model;

use Think\Model;

class BbsModel extends Model
{
    protected $_validate = array(
        //        array('title', 'require', '问题标题必须填写！', 1),
        array('content', 'require', '内容必须填写'),
        array('category1', 'require', '请正确选择分类！', 1),
        array('category2', 'number', '请正确选择分类！', 2),
    );

    protected $_auto = array(
        array('click', '1'),
        array('audit', '0'),
        array('addtime', 'time', 1, 'function'),
        array('replytime', 'time', 3, 'function'),
    );

    /**
     * 获取回答列表
     * @param array        $map  条件
     * @param bool         $page 是否分页
     * @param array|string $sort 排序方式
     * @param int          $num  限制获取条数
     * @return array
     */
    public function get_list($map = array(), $page = false, $sort = '', $num = 10, $startrow = 0)
    {
        // $map, $page, $order, $num, $startrow
        $limit = $num ? $num : 10;

        if (empty($sort)) {
            $sort = 'id DESC';
        }
        if ($page) {
            $count = $this->where($map)->count();
            $Page = pager($count, $limit);
            $limit = $Page->firstRow . ',' . $Page->listRows;
            $page_str = $Page->fshow();
            $list = $this->where($map)->order($sort)->limit($limit)->select();
        } else {
            $list = $this->where($map)->order($sort)->limit($startrow . ',' . $limit)->select();
        }

        if (empty($list)) return array();  // 返回空列表

        $list = array_map(array($this, 'fill'), $list);

        // 获取问题分类信息
        $cat = ytata_get_cache('cat');
        foreach ($list as $index => $question) {
            $_cat = $cat[$question['category2']];
            if (empty($_cat)) {
                $_cat = $cat[$question['category1']];
            }
            $list[$index]['cat'] = $_cat;
        }

        $return['list'] = $list;
        $return['count'] = $page ? $count : count($list);
        $return['page'] = $page_str;

        return $return;
    }

    /**
     * 添加主题
     * @param array $data
     * @param int   $uid 发布者
     */
    public function bbs_add($data, $uid)
    {
        // 如果用户被禁言，则不能发表主题
        $ban = D('UserBan')->chenk_ban($uid);
        if (!empty($ban)) {
            $ret['status']  = false;
            $ret['msg'] = "发表失败，您已经被禁言（{$ban['txt']}），禁言结束时间：{$ban['endtime_str']}";
            return $ret;
        }

        // 保存主题
        if (!$this->create($data)) {
            $ret['status'] = false;
            $ret['msg'] = $this->getError();
            return $ret;
        } else {
            $this->uid = $uid;
        }
        $bid = $this->add();  // 保存主题
        if ($bid) {
            // 添加主题图片
            $imgs = I('post.img');
            if (!empty($imgs)) {
                foreach ($imgs as $img) {
                    $imgdatas[] = array('bid' => $bid, 'img' => $img);
                }
                D('BbsImg')->addAll($imgdatas);
            }
            // 添加主题标签
            $tags = I('post.tag');
            if (!empty($tags)) {
                foreach ($tags as $tag) {
                    $tagid = D('Tag')->get_tagid($tag);
                    $tagdatas[] = compact('bid', 'tagid', 'tag');
                }
                D('BbsTag')->addAll($tagdatas);
                # 添加主题标签相关操作
                // 增加标签的论坛统计
                $tagids = array_column($tagdatas, 'tagid');
                D('Tag')->update_tag_count($tagids, '3');
            }

            # 发布主题相关操作
            // 增加用户发布主题的统计数
            D('User')->update_count($uid, 3);
            D('Task')->exe_add_question($uid);//完成发表主题的任务

            $ret['status'] = true;
            $ret['msg'] = '发布成功';
			$ret['bid'] = $bid;
            return $ret;
        } else {
            $ret['status'] = false;
            $ret['msg'] = '添加失败';
            return $ret;
        }
    }

    /**
     * 获取主题
     * @param int $id
     */
    public function get_bbs_one($id)
    {
        $info = $this->find($id);
        $info = $this->fill($info);
        return $info;
    }

    // 字段填充
    public function fill($item)
    {
		if (empty($item)){
		return false;
		}
        $item['audit_str'] = $this->get_audit_str($item['audit']);
        $item['addtimestr'] = daterange($item['addtime']);
        $item['replytimestr'] = daterange($item['replytime']);
        $item['content_cut'] = cut_str(strip_tags($item['content']), 80);
        $item['url'] = RU('bbs/view', array('id' => $item['id']));
        return $item;
    }

    /**
     * 审核格式化输出（用于后台展示）
     *
     * @param int $audit
     * @return string
     */
    public function get_audit_str($audit)
    {
        $audit = intval($audit);

        $case_str = array(
            -1 => '<span style="color:#999999">未通过</span>',
            0  => '<span style="color:#FF0000">未审核</span>',
            1  => '<span style="color:#009900">已审核</span>'
        );

        return $case_str[$audit];
    }

    public function map_category($category1, $category2 = '')
    {
        $map = array();
        if ($category1 > 0) {
            $map['category1'] = $category1;
        }
        if ($category2 > 0) {
            $map['category2'] = $category2;
        }
        return $map;
    }

    public function map_keywords($key, $key_type = 1)
    {
        $map = array();
        $key_type = (int)$key_type;

        if ($key_type == 1) {
            $map['content'] = array('like', '%' . $key . '%');
        }
        if ($key_type == 2) {
            $map['uid'] = intval($key);
        }

        return $map;
    }

    /**
     * 设置审核类型
     * @param int $type [1-未审核 2-已审核 3-全部]
     */
    public function map_audit($type = 3)
    {
        $map = array();
        $case_type = array(
            1 => '0',
            2 => '1',
            3 => array('IN', array('0', '1'))
        );

        $map['audit'] = $case_type[$type];
        return $map;
    }

    public function map_tagid($tagid)
    {
        $map = array();
        $bids = M('BbsTag')->where(array('tagid' => $tagid))->order('id desc')->getField('bid', true) ?: array();
        $bids = implode(',', $bids);
        $map['id'] = array('IN', $bids);
        return $map;
    }

    /**
     * 删除主题
     *
     * @param $ids
     */
    public function del_bbs($ids,$uid='')
    {
		$ids = is_array($ids) ? implode(",", $ids) : $ids;
        $map['id'] = array('IN',"{$ids}");
		if (!empty($uid)){
		$map['uid'] = intval($uid);
		}
        $uids = $this->where($map)->getField('uid', true);  // 被删除主题的发布用户ID列表
        $tagmap['bid'] = array('IN', $ids);
        $tagids = M('BbsTag')->where($tagmap)->getField('tagid', true);

        $count = $this->where($map)->delete();
        // 相关操作
        if ($count) {
            $delmap['bid'] = array('IN', "{$ids}");
            D('BbsTag')->where($delmap)->delete();
            D('BbsImg')->where($delmap)->delete();
            // 更新用户的讨论统计数
            $uids = array_unique($uids);
            D('User')->update_count($uids,3);
            // 更新话题的主题统计数
            if ($tagids) {
                D('Tag')->set_tag_count($tagids,'count_bbs');
            }
        }
    }

    /**
     * 统计用户的发布讨论数
     *
     * @param int $uid
     * @return int
     */
    public function count_bbs($uid)
    {
        $map['uid'] = intval($uid);
        $map['audit'] = array('EGT', 0);
        return (int)$this->where($map)->count();
    }

    /**
     * 设置审核状态
     * @param int          $state 1=通过 0=未审核 -1=未通过
     * @param array|string $ids
     * @return mixed
     */
    public function bbs_audit($audit, $ids)
    {
        $map['id'] = array('IN', $ids);
        $data['audit'] = $audit;
        $count = $this->where($map)->save($data);

        if ($count) {
            // 更新用户主题数
            $map['id'] = array('IN', $ids);
            $uids = D('Bbs')->where($map)->getField('uid', true);
            $uids = array_unique($uids);
            D('User')->update_count($uids, 3);
        }

        return $count;
    }

    /**
     * 主题点赞
     */
    public function praise($uid, $bid)
    {
        $map['uid'] = $uid;
        $map['bid'] = $bid;
        $praise = M('BbsPraise')->where($map)->find();
        if ($praise) {
            $res['status'] = 2;
            $res['msg'] = '已点过赞';
            return $res;
        }
        $ret = D('BbsPraise')->praise_add($uid, $bid);
        // 点赞失败
        if (!$ret['status']) {
            $res['status'] = 0;
            $res['msg'] = $ret['msg'];
            return $res;
        }

        # 点赞成功相关操作
        // 更新主题的点赞数
        $this->where(array('id' => $bid))->setInc('count_praise');
        $bbs = D('Bbs')->find($bid);
        D('Rank')->add_record('praise', $bbs['uid'], 1);  // 记录排行数据

        $res['status'] = 1;
        $res['msg'] = $ret['msg'];
        $q = M('Bbs')->field('count_praise')->find($bid);
        $res['count_praise'] = $q['count_praise'];
        return $res;
    }

    /**
     * 更新主题的回复统计数
     * @param $bid
     */
    public function update_reply($bid)
    {
        $map['bid'] = $bid;
        $count = M('BbsReply')->where($map)->count();
        $this->where(array('id'=>$bid))->setField('count_reply', $count);
    }

    // 主题关注
    public function follow($bid, $uid)
    {
        $chenk = D('FollowBbs')->chenk_follow_bbs($uid, $bid);
        if ($chenk) {
            D('FollowBbs')->clear_follow_bbs($uid, $bid);
            $count           = D('FollowBbs')->get_follow_count($bid);
            $ajax['status']  = 2;
            $ajax['count']   = $count;
            $ajax['msg'] = '取消关注成功！';
            return $ajax;
        } else {
            D('FollowBbs')->follow_bbs($uid, $bid);
            $count = D('FollowBbs')->get_follow_count($bid);
            # 关注主题相关操作
//            D('UserTrack')->add_track($uid, $qid, 6);//写入个人动态
            $ajax['status']  = 1;
            $ajax['count']   = $count;
            $ajax['msg'] = '关注成功！';
            return $ajax;
        }
    }
}